package java8;

import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class Test3 {
    @Test
    public void test() {
        // stream流创建

        // 通过集合创建
        List<Integer> list = Arrays.asList(1, 2, 0, 6, 5);
        Stream<Integer> stream1 = list.stream();

        // 通过数组
        int[] arr = {1, 3, 5, 2, 4, 0};
        IntStream stream2 = Arrays.stream(arr);

        // 通过Stream.of
        Stream<Integer> stream3 = Stream.of(1, 3, 5, 6, 9, 7, 5);

        // 创建无限流
        Stream<Double> stream4 = Stream.generate(Math::random);
        Stream<Integer> stream5 = Stream.iterate(1, num -> num += 2);
    }

    @Test
    public void test2() {
        // stream流中间操作
        List<Integer> list = Arrays.asList(1, 2, 0, 6, 5);
        Stream<Integer> stream1 = list.stream();
        // 过滤 > 3 的数
        Stream<Integer> stream2 = stream1.filter(num -> num > 3);
        stream2.forEach((n) -> System.out.print(n + " "));

        System.out.println();
    }

    @Test
    public void test3() {
        List<Integer> list = Arrays.asList(1, 2, 0, 6, 5);
        Stream<Integer> stream1 = list.stream();

        Optional<Integer> reduce = stream1.reduce(Integer::sum);
        Integer integer = reduce.get();
        System.out.println(integer);
    }
}
